package com.lbs.jiepiaisi.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lbs.jiepiaisi.R;
import com.lbs.jiepiaisi.activity.WorkHomeOrderAddActivity;
import com.lbs.jiepiaisi.activity.WorkOrderAddActivity;
import com.lbs.jiepiaisi.adapter.WorkOrderListAdapter;
import com.lbs.jiepiaisi.bean.WorkOrderListBean;
import com.lbs.jiepiaisi.biz.WorkOrderBiz;
import com.lbs.jiepiaisi.biz.WorkOrderGetOrderBiz;
import com.lbs.jiepiaisi.utils.ButtonUtil;
import com.lbs.jiepiaisi.utils.Constant;
import com.lbs.jiepiaisi.view.WaitingDialogControll;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * 时间：2018/1/12 15:25
 * 作用：
 */

public class WorkOrderListFragment extends Fragment implements WorkOrderListAdapter.OnItemClickListener{
    private String  type;
    public static final String WORK_TYPE = "work_order_type";
    public static final String WORK_INSTALLID = "work_order_installerId";

    public static final String WORK_ORDER_REFRESH = "work_order_refresh";

    private String installerId;

    private int page = 1;
    private int size = 10;

    WorkOrderReceiver mWorkOrderReceiver;

    RefreshWorkOrderReceiver mRefreshWorkOrderReceiver;

    private ImageView mImage;

    private WorkOrderListAdapter mWorkOrderAdapter;

    private SwipeRefreshLayout swipeRefreshLayout;
    private RecyclerView mWorkOrderRecyclerList;

    private TextView mNoDataTv;

    private boolean isLoading = false;

    private Handler handler = new Handler();

    public static WorkOrderListFragment getInstance(String type,String installerId){
        Bundle args = new Bundle();
        args.putString(WORK_TYPE, type);
        args.putString(WORK_INSTALLID, installerId);
        WorkOrderListFragment pageFragment = new WorkOrderListFragment();
        pageFragment.setArguments(args);
        return pageFragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        type=getArguments().getString(WORK_TYPE);
        installerId=getArguments().getString(WORK_INSTALLID);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_work_order_list, container, false);
        mWorkOrderReceiver = new WorkOrderReceiver();
        getActivity().getApplicationContext().registerReceiver(mWorkOrderReceiver,new IntentFilter(WORK_TYPE + type));
        mRefreshWorkOrderReceiver = new RefreshWorkOrderReceiver();
        getActivity().getApplicationContext().registerReceiver(mRefreshWorkOrderReceiver,new IntentFilter(WORK_ORDER_REFRESH));
        findView(view);
        getExtras();
        setListener();
        return view;
    }

    public void findView(View view){
//        mImage = (ImageView)view.findViewById(R.id.iv_img);
//        Bitmap sourBitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.banner1);
//        mImage.setImageBitmap(ImageWaterMaskUtil.drawTextToRightBottom(getActivity(),sourBitmap,"右下角",12, Color.RED,10,10));
        mWorkOrderRecyclerList = (RecyclerView) view.findViewById(R.id.lv_work_order_list);
        mNoDataTv = (TextView)view.findViewById(R.id.tv_no_record);
        swipeRefreshLayout= (SwipeRefreshLayout) view.findViewById(R.id.swipeRefreshLayout);
        swipeRefreshLayout.setColorSchemeResources(R.color.blue);
//        swipeRefreshLayout.post(new Runnable() {
//            @Override
//            public void run() {
//                swipeRefreshLayout.setRefreshing(false);
//            }
//        });

        //下拉刷新时执行的操作
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Log.e("TAG","开始下拉了");
                        refresh();
                    }
                }, 1000);


            }
        });



    }
    private void getExtras(){
        page=1;
        WorkOrderBiz workOrderBiz = new WorkOrderBiz();
        workOrderBiz.getOrderBiz(page,size,type,installerId,WORK_TYPE + type,false);
    }

    private void setListener(){
        final LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        mWorkOrderRecyclerList.setLayoutManager(layoutManager);
        //展示数据
        mWorkOrderRecyclerList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition();
                if (lastVisibleItemPosition + 1 == mWorkOrderAdapter.getItemCount()) {
                    if (!isLoading) {
                        isLoading = true;
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                page++;
                                isLoading = false;
                                WorkOrderBiz workOrderBiz = new WorkOrderBiz();
                                workOrderBiz.getOrderBiz(page,size,type,installerId,WORK_TYPE + type,true);
                            }
                        }, 1000);
                    }
                }
            }
        });
    }

    private void refresh(){
        //刷新页面
        page = 1;
        mWorkOrderList.clear();
        //刷新页面
        WorkOrderBiz workOrderBiz = new WorkOrderBiz();
        workOrderBiz.getOrderBiz(page,size,type,installerId,WORK_TYPE + type,false);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        getActivity().getApplicationContext().unregisterReceiver(mRefreshWorkOrderReceiver);
        getActivity().getApplicationContext().unregisterReceiver(mWorkOrderReceiver);
    }
    private List<WorkOrderListBean.Result.Item> mWorkOrderList = new ArrayList<>();


    @Override
    public void onItemClick(View view, int position, String flag) {
        Log.e("work",new Gson().toJson(mWorkOrderList.get(position)));
        if(ButtonUtil.isFastClick()){
            if(!flag.contains("4")){
                Intent intent = new Intent(getActivity(), WorkOrderAddActivity.class);
                intent.putExtra("order",new Gson().toJson(mWorkOrderList.get(position)));
                startActivity(intent);
            }else {
                Intent intent = new Intent(getActivity(), WorkHomeOrderAddActivity.class);
                intent.putExtra("order",new Gson().toJson(mWorkOrderList.get(position)));
                startActivity(intent);
            }

        }

    }

    @Override
    public void onActionClick(View view, int position, String flag) {
        if(flag.equals(Constant.WORK_ORDER_NO_GET)){
            WaitingDialogControll.showWaitingDialog(getActivity());
            new WorkOrderGetOrderBiz().getOrderBiz(mWorkOrderList.get(position).getWoId(),Constant.WORK_ORDER_HAVE_GET,mWorkOrderList.get(position).getWorkEqnos(),WORK_ORDER_REFRESH,true);
        }

    }

    //接收工单数据的广播
    class WorkOrderReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            WaitingDialogControll.dismissWaitingDialog();
            WorkOrderListBean mWorkOrderListBean = (WorkOrderListBean)intent.getSerializableExtra(Constant.KEY_DATA);
            boolean isLoadMore = intent.getBooleanExtra(Constant.KEY_DATA2,false);
            swipeRefreshLayout.setRefreshing(false);
            if( mWorkOrderListBean != null && mWorkOrderListBean.getStatus() == Constant.STATUS_OK){
                if(mWorkOrderListBean.getResult() != null && mWorkOrderListBean.getResult().getItems() != null && mWorkOrderListBean.getResult().getItems().size() != 0){
                    if(!isLoadMore || mWorkOrderAdapter == null){
                        mWorkOrderList.clear();
                        mWorkOrderList.addAll(mWorkOrderListBean.getResult().getItems());
                        mWorkOrderAdapter = new WorkOrderListAdapter(getActivity(),mWorkOrderList,type);
                        mWorkOrderRecyclerList.setAdapter(mWorkOrderAdapter);
                        mWorkOrderAdapter.setOnItemClickListener(WorkOrderListFragment.this);
                    }else {
                        mWorkOrderList.addAll(mWorkOrderListBean.getResult().getItems());
                        mWorkOrderAdapter.notifyDataSetChanged();
                    }
                }else {
                    if(mWorkOrderAdapter != null) {
                        mWorkOrderAdapter.setLoadMore(false);
                        mWorkOrderAdapter.notifyDataSetChanged();
                    }else {
                        //swipeRefreshLayout.setVisibility(View.GONE);
                        mNoDataTv.setVisibility(View.VISIBLE);
                    }
                }
            } else if(mWorkOrderListBean != null && mWorkOrderListBean.getStatus() == Constant.STATUS_NETWORK_ERROR){
                if(mWorkOrderAdapter != null) {
                    mWorkOrderAdapter.setLoadMore(false);
                    mWorkOrderAdapter.notifyDataSetChanged();
                }else {
                    //swipeRefreshLayout.setVisibility(View.GONE);
                    mNoDataTv.setVisibility(View.VISIBLE);
                }

                //Toast.makeText(mContext, "没有更多数据", Toast.LENGTH_SHORT).show();
            }else if(mWorkOrderListBean != null &&  mWorkOrderListBean.getStatus() == Constant.STATUS_NO_NET){
                Toast.makeText(getActivity(), "请检查网络", Toast.LENGTH_SHORT).show();
            }else {
                if(mWorkOrderAdapter != null) {
                    mWorkOrderAdapter.setLoadMore(false);
                    mWorkOrderAdapter.notifyDataSetChanged();
                }else {
                    //swipeRefreshLayout.setVisibility(View.GONE);
                    mNoDataTv.setVisibility(View.VISIBLE);
                }
            }
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        refresh();
    }

    //刷新工单数据
    class RefreshWorkOrderReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            int status = intent.getIntExtra(Constant.KEY_DATA,-1);
            String update = intent.getStringExtra(Constant.KEY_DATA2);
            boolean isJieDan = intent.getBooleanExtra(Constant.KEY_DATA3,false);
            if(status == Constant.STATUS_OK){
                WaitingDialogControll.dismissWaitingDialog();
                if(isJieDan){
                    try {
                        Context context1 = getActivity();
                        if(context1 != null){
                            Toast.makeText(context, "接单成功", Toast.LENGTH_LONG).show();
                        }
                    }catch (Exception e){
                        Log.e("WorkOrderListFragment","==>302");
                    }
                }
                refresh();
            }else {
                WaitingDialogControll.dismissWaitingDialog();
//                if(ToastUtil.isFastShow()){
                    Toast.makeText(context, "操作失败，请重新操作", Toast.LENGTH_LONG).show();
//                }
            }

        }
    }
}
